package client

import (
	"asuOfficialApi/comm"
	"asuOfficialApi/model"
	"asuOfficialApi/service"
	"asuOfficialApi/vo"
	"asuOfficialApi/web/middleware"
	"github.com/kataras/iris"
	"gopkg.in/go-playground/validator.v9"
	"strings"
)

type UserController struct {
	Ctx          iris.Context
	ServiceUser  service.UserService
	ServiceToken service.TokenService
}

// http://localhost:8080/client/user/anno/register
func (c *UserController) PostUserAnnoRegister() iris.Map {
	var userForm = &vo.UserForm{
		Username: c.Ctx.PostValue("username"),
		Password: c.Ctx.PostValue("password"),
	}
	if err := middleware.ValidateStruct(userForm); err != nil {
		if errs, ok := err.(validator.ValidationErrors); ok {
			return comm.Fail(comm.ErrorParamFormat, errs[0].Translate(middleware.Translate()))
		}
	}

	if user, err := c.ServiceUser.Register(userForm.Username, userForm.Password); err != nil {
		return comm.Fail(err.Code, err.Error.Error())
	} else {
		data := map[string]interface{}{"user_id": user.Id}
		return comm.Success(data)
	}
}

// http://localhost:8080/client/user/anno/login
func (c *UserController) PostUserAnnoLogin() iris.Map {
	var userForm = &vo.UserForm{
		Username: c.Ctx.PostValue("username"),
		Password: c.Ctx.PostValue("password"),
	}
	if err := middleware.ValidateStruct(userForm); err != nil {
		if errs, ok := err.(validator.ValidationErrors); ok {
			return comm.Fail(comm.ErrorParamFormat, errs[0].Translate(middleware.Translate()))
		}
	}

	if user, err := c.ServiceUser.Login(userForm.Username, userForm.Password); err != nil {
		return comm.Fail(err.Code, err.Error.Error())
	} else {
		var token string
		tokenEntity := c.ServiceToken.GetTokenById(user.Id)

		if tokenEntity != nil && tokenEntity.Id > 0 {
			token = tokenEntity.Token
		} else {
			tokenModel := c.ServiceToken.Insert(user.Id, model.TokenUserTypeUser)
			token = tokenModel.Token
		}

		data := map[string]interface{}{"user": user, "token": token}
		return comm.Success(data)
	}
}

// http://localhost:8080/client/user/info
func (c *UserController) GetUserInfo() iris.Map {
	userId, _ := c.Ctx.Values().GetInt64("user_id")
	if user, e := c.ServiceUser.FindById(userId); e != nil {
		return comm.Fail(e.Code, e.Error.Error())
	} else {
		data := map[string]interface{}{"user": user}
		return comm.Success(data)
	}
}

// http://localhost:8080/client/user/logout
func (c *UserController) PostUserLogout() iris.Map {
	token := strings.TrimSpace(c.Ctx.URLParam("token"))
	err := c.ServiceToken.DeleteToken(token)
	if err != nil {
		return comm.Fail(err.Code, err.Error.Error())
	}

	c.Ctx.Values().Set("user_id", 0)
	c.Ctx.Values().Set("user_type", 0)
	return comm.Success("token删除成功")
}
